package eva.savant.business.material.view

import eva.savant.core.view.Maestro
import eva.savant.businessobject.mt.Jerarquia

import org.primefaces.model.TreeNode
import org.primefaces.model.DefaultTreeNode
import org.primefaces.event.NodeSelectEvent
import javax.faces.bean.ManagedBean
import javax.faces.bean.SessionScoped
import javax.annotation.PostConstruct

@SessionScoped
@ManagedBean(name = 'IMJerarquia')
public class IMJerarquia extends Maestro {

  TreeNode root, selectedNode

  def list

  @PostConstruct
  public void cleanEntity() {

    entity= new Jerarquia(); init()

    list= new HashMap<String,DefaultTreeNode>()
  }

  public List findLsEntity() {

    lsEntity= find(Jerarquia.class,'order by nivel')

    buildTree(); return lsEntity
  }

  public void buildTree() {

    root= new DefaultTreeNode('Root',null)

    list= new HashMap<String,DefaultTreeNode>()


    for(x in lsEntity) {

    def node= new DefaultTreeNode(x, null)

    def id = x.id + ''; list.put(id, node)


    def tam= id.length()

    def end= (tam-2) > 0? (tam-2) : 0


    def parentId= id.substring(0,end)

    def parent= list[parentId]

    node.parent= parent != null? parent : root

    if(node.data.nivel < 2) node.expanded= true }
  }

  public void onNodeSelect(NodeSelectEvent event) {

    form= true; editEntity(selectedNode.data.id)
  }

  public void editEntity(Object id) {

    entity= get(Jerarquia.class, id)

    if(entity == null) return; list[entity.id].selected = true


    for(int i= entity.id.length()-2; i > 2; i=i-2)

    list[entity.id.substring(0,i)].expanded= true
  }

}
